package com.itheima.contorller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.common.R;
import com.itheima.upload.OssProperties;
import com.itheima.contorller.utils.ConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author 12441
 * @Date 2022/8/11 19:31
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class UploadController<ResultJson> {

    @Autowired
    private OssProperties ossProperties;

@PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //获取地域节点
        String endPoint = ConstantPropertiesUtils.END_POINT;
        //id
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        //密钥
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        //bucket名称
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;


        try {
            //创建OSS实例
            OSS oss = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String suffixName = FileUtil.extName(fileName);
            //防止文件名重复使用uuid重新拼接生成文件名
            fileName = IdUtil.randomUUID() + "." + suffixName;
            //调用oss方法实现上传
            oss.putObject(bucketName, fileName, inputStream);
            //关闭资源
            oss.shutdown();
            String url="https://ofo1244.oss-cn-hangzhou.aliyuncs.com/"+fileName;

            return R.success(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("上传失败");
    }
}
